package com.binary.coder.gift.core.common.excel;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelHttpExporter extends ExcelExporter {

    public static ExcelHttpExporter create() {
        return new ExcelHttpExporter();
    }

    public String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("User-Agent").toLowerCase();
        if (UserAgent.indexOf("firefox") >= 0) {
            return "FF";
        } else if (UserAgent.indexOf("safari") >= 0) {
            return "Chrome";
        } else {
            return "IE";
        }
    }

    ///////初始化/////////////

    public ExcelHttpExporter init(HttpServletRequest request, HttpServletResponse response, String name, List<String> header) throws UnsupportedEncodingException {
        return init(request, response, name, header, null);
    }

    public ExcelHttpExporter init(HttpServletRequest request, HttpServletResponse response, String name, List<String> header, Map<String, String> headerAlias) throws UnsupportedEncodingException {
        String fileName = "导出-" + name + ".xlsx";
        if ("IE".equals(getBrowser(request))) {
            fileName = new String(java.net.URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            this.init(outputStream, name, header, headerAlias);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }

        return this;
    }
}
